package com.lepu.app.fun.my;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.my.adapter.AdapterMyAddressManageList;
import com.lepu.app.fun.my.bean.BeanMyAddressManage;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

public class MyAddressManageActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,
		AsyncRequest, Observer {

	private static final String REQUEST_MY_ADDRESS = "request_my_address";
	private static final String REQUEST_UPDATE_ADDRESS = "request_update_address";
	private static final String REQUEST_DELETE_ADDRESS = "request_delete_address";

	private TextView mAddressDefaultTextView;
	private ArrayList<BeanMyAddressManage> mDataList = null;
	private AdapterMyAddressManageList mDataAdapter = null;
	private int mCurrentIndex = 0;

	private ListView mDataListView = null;
	private LinearLayout mNoDataLayout = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_address_manage_activity);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		ObserverManager.getInstance().removeObserver(
				ObserverConst.NOTIFY_MY_ADDRESS_MANAGE_CHANGE);
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("收货信息");
		topbar.setRightText("新增");
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setOnTopbarNewRightButtonListener(this);

		mDataListView = (ListView) findViewById(R.id.dataListView);
		mNoDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);

		ObserverManager.getInstance().addObserver(
				ObserverConst.NOTIFY_MY_ADDRESS_MANAGE_CHANGE,this);
		requestData(true);
	}

	private void updateNoDataView() {
		if (mDataList == null || mDataList.size() == 0) {
			mNoDataLayout.setVisibility(View.VISIBLE);
			mDataListView.setVisibility(View.GONE);
		} else {
			mNoDataLayout.setVisibility(View.GONE);
			mDataListView.setVisibility(View.VISIBLE);
		}
	}

	private void requestData(boolean needProgress) {

		if (needProgress) {
			showProgressDialog();
		}
		String url = Setting.getMyAddressUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post_main(url, map, null, this, REQUEST_MY_ADDRESS,
				true,false,true);
	}

	public void requestSetDefaultAddress(BeanMyAddressManage item,
			TextView addressDefaultTextView, int position) {
		
		if(addressDefaultTextView.isSelected())
		{
			return;
		}
		
		mAddressDefaultTextView = addressDefaultTextView;
		mCurrentIndex = position;

		String url = Setting.getUpdateUserAddressUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("AID", item.AID);
			params.put("ReceiverName", item.ReceiverName);
			params.put("ReceiverPhone", item.ReceiverPhone);
			params.put("AreaID", "");// test no use
			params.put("ReceiverAddress", item.ReceiverAddress);
			params.put("IsDefault", "1");

		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog();
		ApiClient.http_post_main(url, map, null, this, REQUEST_UPDATE_ADDRESS,
				true);
	}
	
	public void requestDeleteAddress(final int position,final String aid) {
		
		String message = "您确认删除这个收货地址吗?";
		MyDialog dialog = new MyDialog(this)
				.setMessage(message)
				.setNegativeButton(R.string.app_cancel,
						R.drawable.btn_cancel_selector, R.color.color_white,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.app_ok,
						R.drawable.btn_ok_selector, R.color.color_white,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								
								mCurrentIndex = position;

								String url = Setting.getDeleteUserAddressUrl();

								Map<String, Object> map = new HashMap<String, Object>();
								JSONObject params = new JSONObject();
								try {
									params.put("DeviceID", Setting.DEVICEID);
									params.put("ApplicationID", Setting.APPLICATIONID);

									params.put("UserID", LoginUtil.getUserId());
									params.put("LoginToken", LoginUtil.getLoginToken());

									params.put("AID", aid);
								} catch (Exception e) {
								}
								map.put("ht", params);

								showProgressDialog();
								ApiClient.http_post_main(url, map, null, MyAddressManageActivity.this, REQUEST_DELETE_ADDRESS,
										true);
							}
						});

		dialog.create(null);
		dialog.showMyDialog();
	}


	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_MY_ADDRESS)) {
			hideProgressDialog();

			mDataList = BeanMyAddressManage.parseJsonData((String)data);
			mDataAdapter = new AdapterMyAddressManageList(this,
					mDataList);
			mDataListView.setAdapter(mDataAdapter);

			updateNoDataView();

		} else if (object.equals(REQUEST_UPDATE_ADDRESS)) {
			hideProgressDialog();
			
			for(int i=0;i<mDataList.size();i++)
			{
				String defaultTag = String.format("default_address_%d", i);
				TextView defaultAddressTextView = (TextView) mDataListView.findViewWithTag(defaultTag);
				if(defaultAddressTextView != null)
				{
					defaultAddressTextView.setSelected(false);
				}
				mDataList.get(i).IsDefault = "0";
			}

			mAddressDefaultTextView.setSelected(true);
			mDataList.get(mCurrentIndex).IsDefault = "1";
		} else if (object.equals(REQUEST_DELETE_ADDRESS)) {
			hideProgressDialog();

			mDataList.remove(mCurrentIndex);
			mDataAdapter.notifyDataSetChanged();
			updateNoDataView();
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String data) {
		if (object.equals(REQUEST_MY_ADDRESS)) {
			hideProgressDialog();

			updateNoDataView();
		} else if (object.equals(REQUEST_UPDATE_ADDRESS)) {
			hideProgressDialog();
		} else if (object.equals(REQUEST_DELETE_ADDRESS)) {
			hideProgressDialog();
		}
	}

	public void jumpNewAddress(boolean isNewAdd, BeanMyAddressManage item) {
		if (isNewAdd) {
			// 判断最多有10个地址
			if (mDataList != null && mDataList.size() >= 10) {
				UIHelper.showToast(this, "最多新增10个收货地址");
				return;
			}
		}
		Intent intent = new Intent(this, MyAddressActivity.class);
		intent.putExtra("IsNewAdd", isNewAdd);
		if (!isNewAdd) {
			intent.putExtra("BeanMyAddressManage", item);
		}else{
			int count = 0;
			if(mDataList != null){
				count = mDataList.size();
			}
			intent.putExtra("CurrentAddressCount", count);
		}
		startActivity(intent, true);
	}

	@Override
	public void onTopbarRightButtonSelected() {
		jumpNewAddress(true, null);
	}

	@Override
	public void notify(String name, Object sender, Object data) {
		if (name.equals(ObserverConst.NOTIFY_MY_ADDRESS_MANAGE_CHANGE)) {
			requestData(false);
		}
	}

}
